﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Sharp.DataTransferObject;
using Sharp.Infrastructure.WebApiClient;
using Sharp.Portal.Mvc;
using Sharp.ServiceContracts;
using Sharp.WebBooter.Areas.Platform.Models;
using Sharp.Portal.Mvc.Models;
using System.Threading.Tasks;
using Sharp.Infrastructure;

namespace Sharp.WebBooter.Areas.Platform.Controllers
{
    [Authorize]
    public class PermissionController : SharpController
    {
        public ActionResult Index(string owner, int ownerId)
        {
            IEnumerable<PermissionDTO> list;
            IEnumerable<PermissionDTO> selectedList;
            var model = new PermissionViewModel
            {
                Owner = Request.Params["owner"],
                OwnerId = Request.Params["ownerId"],
                Trees = new Dictionary<string, zTreeNode>()
            };

            using (var proxy = new WebApiClientServiceProxy<IUserService>())
            {
                list = proxy.Channel.AllPermissions().Result;
                if (owner == "user")
                {
                    selectedList = proxy.Channel.GetPermissionById(ownerId).Result;
                }
                else
                {
                    selectedList = proxy.Channel.GetPermissionByRoleId(ownerId).Result;
                }
            }
            using (var proxy = new WebApiClientServiceProxy<IPlatformService>())
            {
                model.SubSystems = proxy.Channel.GetSubSystems();
            }
            foreach (var sub in model.SubSystems)
            {
                model.Trees.Add(sub.Code, new zTreeNode());

                Build(list.Where(x => x.SystemCode == sub.Code), selectedList, model.Trees[sub.Code], null);
            }
            return View(model);
        }

        public ActionResult Available()
        {

            IEnumerable<PermissionDTO> list;
            var newList = new List<PermissionIndexViewModel>();
            using (var proxy = new WebApiClientServiceProxy<IUserService>())
            {
                list = proxy.Channel.AllPermissions().Result;
            }

            Build(list, newList, null);

            return View(newList);
        }

        private void Build(IEnumerable<PermissionDTO> table, List<PermissionIndexViewModel> node, Guid? parentValue)
        {
            var rows = table.Where(x => x.ParentId == parentValue).OrderBy(x => x.OrderIndex);
            foreach (var row in rows)
            {
                var _node = new PermissionIndexViewModel();
                _node.Title = row.Title;
                _node.Id = row.Id;
                _node.ParentId = row.ParentId;
                if (row.ParentId == null)
                {
                    _node.Itemclass = string.Format("treegrid-{0}", row.Id);
                }
                else
                {
                    _node.Itemclass = string.Format("treegrid-{0} treegrid-parent-{1}", row.Id, row.ParentId);
                }


                node.Add(_node);

                Build(table, node, row.Id);
            }
        }

        private void Build(IEnumerable<PermissionDTO> table, IEnumerable<PermissionDTO> selectedList, zTreeNode node,
            Guid? parentValue)
        {
            var rows = table.Where(x => x.ParentId == parentValue).OrderBy(x => x.OrderIndex);
            foreach (var row in rows)
            {
                var _node = new zTreeNode
                {
                    Name = row.Title,
                    Id = row.Id.ToString(),
                    ParentId = row.ParentId == null ? row.ParentId.ToString() : null,
                    Raw = row,
                    Checked = selectedList.Any(x => x.Id == row.Id)
                };

                node.Children.Add(_node);
                node.IsParent = node.Children.Any();

                Build(table, selectedList, _node, row.Id);
            }
        }

        

        public ActionResult Save(Guid[] permissionIds, string owner, int ownerId)
        {
            using (var proxy = new WebApiClientServiceProxy<IUserService>())
            {
                var res = proxy.Channel.SavePermission(permissionIds, owner, ownerId);

                return this.JsonNet(res);
            }
        }

        public async Task<ActionResult> Org(int roleId)
        {
            IEnumerable<OrgDTO> allOrgs;
            using (var proxy = new WebApiClientServiceProxy<IEnterpriseService>())
            {
                allOrgs = await proxy.Channel.GetOrgs();
            }
            ViewBag.RoleId = roleId;

            var vm = new zTreeNode();
            OrgController.Build(allOrgs, vm, null);

            RoleDTO role;
            using (var proxy = new WebApiClientServiceProxy<IUserService>())
            {
                role = proxy.Channel.GetRoleByKey(roleId);
            }

            ZTreeChecked(role.AuthorizedOrgs.Select(x => x.Id.ToString()).ToArray(), vm);

            return View(vm);
        }

        private void ZTreeChecked(string[] orage, zTreeNode node)
        {
            node.Checked = orage.Any(x => x == node.Id);

            foreach (var item in node.Children)
            {
                ZTreeChecked(orage, item);
            }
        }

        public ActionResult SaveOrgData(Guid[] orgIds, int roleId)
        {
            Result res;
            using (var proxy = new WebApiClientServiceProxy<IUserService>())
            {
                res = proxy.Channel.SaveOrgPermission(orgIds, roleId);
            }
            return this.JsonNet(res);
        }
    }
}